/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.dntuan.greeting;

import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.Chunk;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfOutline;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfAction;
import java.io.FileOutputStream;

/**
 * Adding bookmark or outline tree to PDF
 * @author dang nhu tuan
 */
public class Outline {

    public Outline() throws Exception {

        Document document = new Document();
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream("D:/outline.pdf"));
        document.open();

        /*
         * Create 3 pages and set destination to titles.
         * Add 2 sub destination in page 2.
         */
        document.add(new Chunk("Chapter 1. Introduce the iText library").setLocalDestination("1"));
        document.newPage();

        document.add(new Chunk("Chapter 2. The first example").setLocalDestination("2"));
        document.add(new Paragraph(new Chunk("Sub 2.1. Download jar files").setLocalDestination("2.1")));
        document.add(new Paragraph(new Chunk("Sub 2.2. Write codes").setLocalDestination("2.2")));
        document.newPage();

        document.add(new Chunk("Chapter 3. Conclusion").setLocalDestination("3"));

        // get the root of the ouline tree
        PdfContentByte cb = writer.getDirectContent();
        PdfOutline root = cb.getRootOutline();

        /*
         * add bookmarks for each pages and 2 sub sections to page 2.
         * Bookmark expanded by default. You can collapse the tree with code
         * <code>oline2.setOpen(false);</code>
         */
        PdfOutline oline1 = new PdfOutline(root,
                PdfAction.gotoLocalPage("1", false), "1. Chapter 1");

        PdfOutline oline2 = new PdfOutline(root,
                PdfAction.gotoLocalPage("2", false), "2. Chapter 2");
        oline2.setOpen(false);
        PdfOutline oline2_1 = new PdfOutline(oline2,
                PdfAction.gotoLocalPage("2.1", false), "2.1 Sub 2.1");
        PdfOutline oline2_2 = new PdfOutline(oline2,
                PdfAction.gotoLocalPage("2.2", false), "2.2 Sub 2.2");

        PdfOutline oline3 = new PdfOutline(root,
                PdfAction.gotoLocalPage("3", false), "3. Chapter 3");

        document.close();
    }

    public static void main(String[] args) {
        try {
            Outline outline = new Outline();
        } catch (Exception e) {
            System.out.println(e);
        }

    }
}
